package com.changgou.controller;

import com.changgou.file.FastDFSFile;
import com.changgou.util.FastDFSClientUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


/**
 * Created by zhangyuhong
 * Date:2020/5/7
 */
@RestController
public class UploadController {

    /**
     * http://localhost:18082/upload
     * 上传文件接口
     * 用postMan测试的是需要注意:Headers中要增加
     * Key：Content-Type  Value：multipart/form-data  body选择form-data,然后key:填写file(选择file) value:选择文件
     *
     * @param file 要上传的图片
     * @return 图片的路径本身
     */
    @PostMapping(value = "/upload")
    public String upload(MultipartFile file) {
        try {
            if (!file.isEmpty()) {
                byte[] bytes = file.getBytes();//strore somewhere  存储到fastdfs即可
                FastDFSFile fastDFSFile = new FastDFSFile();
                fastDFSFile.setName(file.getOriginalFilename());
                fastDFSFile.setContent(bytes);
                fastDFSFile.setExt(StringUtils.getFilenameExtension(file.getOriginalFilename())); //获取扩展名的
                // upload[0]   group1
                // upload[1]   M00/00/00/wKjThF6ycJeAW-ZiAACAThdn_1U074.jpg
                String[] upload = FastDFSClientUtil.upload(fastDFSFile);
                // 浏览器要访问的真正的路径 http://192.168.211.132:8080/group1/M00/00/00/wKjThF6yZjOABCvFAACAThdn_1U976.jpg
                return "http://192.168.211.132:8080/" + upload[0] + "/" + upload[1];
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
